var utils = require('common/utils');

module.exports = lazyload;

/**
 * @description lazyload img specify with class and data-src
 * @param {object} option
 * @example
 * lazyload({
 *  className: "lazyload",
 *  threshold: 0
 * })
 */
function lazyload(option) {
  console.warn('=== lazy ====', Date.now());
  optionCheck(option);
  var defaultOption = {
    className: 'lazyload',
    threshold: 0, // 距离顶部的距离阈值
    callback: undefined  // img load 触发后的回调
  };
  var opt = option
    ? utils.mergeObj(Object.create(null), defaultOption, option)
    : defaultOption;
  var imgs = document.querySelectorAll('.' + opt.className);
  console.log('lazyload imgs:', imgs.length);
  for (var img of imgs) {
    if (startFetch(img, opt.threshold, opt.el && document.querySelector(opt.el))) {
      loadImg(img, opt.className, option.callback);
    }
  }
}

function optionCheck(option) {
  if (!option) return;
  if (!utils.isObject(option)) {
    throw new Error('参数 option 必须是对象类型');
  }
  if (option.className !== undefined && !utils.isString(option.className)) {
    throw new Error('option.className 必须是字符串类型');
  }
  if (option.threshold !== undefined && !utils.isNumber(option.threshold)) {
    throw new Error('option.threshold 必须是数字类型');
  }
}

function startFetch(img, threshold, container) {
  var top = img.getBoundingClientRect().top;
  if (!container) {
    return top <= window.innerHeight + threshold;
  }
  return top <= container.getBoundingClientRect().bottom + threshold;
}

function loadImg(img, className, cb) {
  var image = new Image();
  var realSrc = img.getAttribute('data-src');
  image.src = realSrc;
  image.addEventListener('load', function () {
    img.src = realSrc;
    img.classList.remove(className);
    cb && cb(realSrc);
  });
}
